/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import com.sun.org.apache.bcel.internal.util.ByteSequence;
import dao.CityDAOImpl;
import dao.DAOFactory;
import dao.DistanceDAOImpl;
import hibernate.entityes.City;
import hibernate.entityes.Distance;
import hibernate.entityes.DistancePK;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author 11
 */
public class UploadAction implements Action {

    @Override
    public String perform(HttpServletRequest request, HttpServletResponse response) {
        try {
            DiskFileItemFactory factoryFile = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factoryFile);
            List items = upload.parseRequest(request);
            Iterator i = items.iterator();
            byte[] data = null;
            while (i.hasNext()) {
                FileItem fileitem = (FileItem) i.next();
                if (!fileitem.isFormField()) {
                    data = fileitem.get();
                }
            }
            InputStream uploadedFile = new ByteSequence(data);

            try {
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document doc = documentBuilder.parse(uploadedFile);
                doc.getDocumentElement().normalize();

                if (doc.getDocumentElement().getTagName()
                        .equals("citiesanddistances")) {
                    NodeList cities = doc.getElementsByTagName("cities");
                    NodeList distances = doc.getElementsByTagName("distancetables");

                    for (int j = 0; j < cities.getLength(); ++j) {
                        NodeList city = cities.item(j).getChildNodes();
                        for (int k = 0; k < city.getLength(); k++) {
                            String name = ((Element) city.item(k))
                                    .getElementsByTagName("name")
                                    .item(0).getChildNodes()
                                    .item(0).getNodeValue();
                            double latitude = Double.parseDouble(((Element) city.item(k))
                                    .getElementsByTagName("latitude")
                                    .item(0).getChildNodes()
                                    .item(0).getNodeValue());
                            double longitude = Double.parseDouble(((Element) city.item(k))
                                    .getElementsByTagName("longitude")
                                    .item(0).getChildNodes()
                                    .item(0).getNodeValue());
                            CityDAOImpl daocity = DAOFactory.getHibernateDAOFactory().getCityDAOImpl();
                            City newCity = new City(name, latitude, longitude);
                            daocity.saveElement(newCity);
                       }
                    }

                    for (int j = 0; j < distances.getLength(); ++j) {
                        NodeList distance = distances.item(j).getChildNodes();
                        for (int k = 0; k < distance.getLength(); k++) {
                            String fromCity = ((Element) distance.item(k))
                                    .getElementsByTagName("fromcity")
                                    .item(0).getChildNodes()
                                    .item(0).getNodeValue();
                            String toCity = ((Element) distance.item(k))
                                    .getElementsByTagName("tocity")
                                    .item(0).getChildNodes()
                                    .item(0).getNodeValue();
                            double distanceValue = Double.parseDouble(((Element) distance.item(k))
                                    .getElementsByTagName("distance")
                                    .item(0).getChildNodes()
                                    .item(0).getNodeValue());
                            DistanceDAOImpl daodistance = DAOFactory.getHibernateDAOFactory().getDistanceDAOImpl();
                            DistancePK distancePK = new DistancePK(fromCity, toCity);
                            Distance newDistanceTable = new Distance(distancePK, distanceValue);
                            daodistance.saveElement(newDistanceTable);
                        }
                    }
                }
            } catch (Exception exc) {
                exc.printStackTrace();
            }
            try {
                response.getWriter().print("All Cities And Distance upload to database");
            } catch (IOException ex) {
                Logger.getLogger(UploadAction.class.getName()).log(Level.SEVERE, null, ex);
            }

        } catch (FileUploadException fupexc) {
            fupexc.printStackTrace();
        }
        return null;
    }
}
